package com.roast.services.my;

import com.roast.util.QueryObject;
import com.roast.domain.*;
import com.roast.util.QueryBeanFactory;

public class FindIMPL extends GeneralSO implements Find {

    private UserData user;
    private QueryObject queryObject;
    private DomainObject fromDB;

    @Override
    public int find(UserData user) {
        return new FindIMPL().generalExecution(user);
    }

    @Override
    protected int executeSO(Object obj) {
        if (!setUser(obj)) {
            return 10301;
        }
        if (!user.isEmailSet()) {
            return 10302;
        }
        if (!setQuery()) {
            return 10303;
        }
        if (!isUserExist()) {
            return 10304;
        }
        if (!copyObject(obj)) {
            return 10305;
        }
        return 10300;
    }

    private boolean setUser(Object obj) {
        try {
            this.user = (UserData) obj;
            return true;
        } catch (ClassCastException ex) {
            return false;
        }
    }

    private boolean setQuery() {
        queryObject = QueryBeanFactory.getBean("readUserByParametar");

        if (queryObject != null) {
            queryObject.addParametar("femail", user.getEmail());
            return true;
        } else {
            return false;
        }
    }

    private boolean isUserExist() {
        fromDB = dbbr.readOneByParametar(queryObject);
        return queryObject.getSignal() == 10030;
    }

    private boolean copyObject(Object obj) {
        try {
            return ((UserData) obj).copyObject(fromDB);
        } catch (ClassCastException ex) {
            return false;
        }
    }

    @Override
    protected boolean executeState(int signal) {
        switch (signal) {
            case 10300:
                showOperationState(signal, "_find: User exist.");
                return true;
            case 10301:
                showOperationState(signal, "_find:ERROR: Class cast exception.");
                return false;
            case 10302:
                showOperationState(signal, "_find:ERROR: You did not set user email address!");
                return false;
            case 10303:
                showOperationState(signal, "_find:ERROR: Fail to set query.");
                return false;
            case 10304:
                showOperationState(signal, "_find:ERROR: User dose not exist!");
                return false;
            case 10305:
                showOperationState(signal, "_find:ERROR: Fail to copy object.");
                return false;
        }
        return false;
    }
}
